<template>
  <div class="cmykBox list-r-8" :style="{
    width: proxy.$size(width, '100%'),
  }">
    <el-input v-model="keyword.c" ref="cmykBox1" @input="validateInput($event, 'c')" @focus="focusBtn(cmykBox1)"
      @change="onChangeBtn(cmykBox2)">
      <template #prefix>
        <span>C</span>
      </template>
    </el-input>
    <el-input v-model="keyword.m" ref="cmykBox2" @input="validateInput($event, 'm')" @focus="focusBtn(cmykBox2)"
      @change="onChangeBtn(cmykBox3)">
      <template #prefix>
        <span>M</span>
      </template>
    </el-input>
    <el-input v-model="keyword.y" ref="cmykBox3" @input="validateInput($event, 'y')" @focus="focusBtn(cmykBox3)"
      @change="onChangeBtn(cmykBox4)">
      <template #prefix>
        <span>Y</span>
      </template>
    </el-input>
    <el-input v-model="keyword.k" ref="cmykBox4" @input="validateInput($event, 'k')" @focus="focusBtn(cmykBox4)"
      @change="onChangeBtn(cmykBox1)">
      <template #prefix>
        <span>K</span>
      </template>
    </el-input>
    <div class="el-color-picker__trigger">
      <span class="el-color-picker__color" :style="{
        backgroundColor: cmykToHex(keyword),
      }"></span>
    </div>
  </div>
</template>
<script setup lang="ts">
import { cmykToHex } from '@/utils/color';
import { getCurrentInstance, reactive, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance() as any;
//获取父级数据
const props = withDefaults(
  defineProps<{
    data: any;
    dataName?: any;
    width?: string | number;
  }>(),
  {

  },
);
const cmykBox1 = ref(null)
const cmykBox2 = ref(null)
const cmykBox3 = ref(null)
const cmykBox4 = ref(null)
const keyword = computed({
  get() {
    return props.dataName ? props.data[props.dataName] : props.data;
  },
  set(val) {
    if (props.dataName) {
      props.data[props.dataName] = val
    } else {
      props.data = val;
    }
  },
});
/**
 * 验证并修正输入值
 * @param value 输入框中的当前值
 */
const validateInput = (value: string, key: string) => {
  // 尝试将输入转换为整数
  let intValue = parseInt(value, 10);

  // 如果转换失败或者输入为空，则设置为默认值0
  if (isNaN(intValue)) {
    intValue = 0;
  }

  // 确保值在0到255之间
  if (intValue < 0) {
    intValue = 0;
  } else if (intValue > 100) {
    intValue = 100;
  }
  let _data = props.dataName ? props.data[props.dataName] : props.data
  // 更新 inputValue，确保显示的是有效的整数值
  _data[key] = intValue.toString();
};
const onChangeBtn = (nextRef: any) => {
  nextRef.focus()
  nextRef.select()
};
const focusBtn = (nextRef: any) => {
  nextRef.select()
};
const emit = defineEmits<{
  //fn为父组件引入子组件是定义的子组件事件属性，可随意定义
  (event: 'changeBtn', val: any, form: any): void;
}>();

onMounted(() => {

});
</script>
<style scoped lang="scss">
.cmykBox {
  display: flex;
  align-items: center;

  .el-input {
    flex: 1;
  }

  .colorBg {
    border: 1px solid var(--el-border-color);
    display: inline-flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    height: 32px;
    width: 32px;
  }
}
</style>
